import { CustomPage, CustomTable } from '@/components/index.jsx';
import { LIMIT } from '@/constants/pageConstant.js';
import ModalUtil from '@/utils/modal.js';
import { Button, Card, Flex, Form, Input, InputNumber } from 'antd';
import { UserApi } from '@/api/user/api.js';
import { useEffect, useRef, useState } from 'react';
import { SPACE } from '@/constants/themeConstant.js';
import { columns } from '@/pages/UserManage/columns.jsx';
import UserFormModal from '@/pages/UserManage/widget/UserFormModal/index.jsx';

export default function UserManage() {
  // 表格页码
  const [pageNo, setPageNo] = useState(1);
  // 表格分页
  const [pageSize, setPageSize] = useState(LIMIT);
  // 搜索表单
  const [searchForm] = Form.useForm();
  // 表格
  const tableRef = useRef();
  // 搜索条件
  const [searchQuery, setSearchQuery] = useState({});
  // 发请求标志
  const [shouldRequest, setShouldRequest] = useState(false);
  // 表单弹窗
  const formRef = useRef();

  // 表格选中项
  const rowSelection = {
    type: 'checkbox',
    fixed: true
  };

  useEffect(() => {
    if (shouldRequest) {
      setShouldRequest(false);
    }
  }, [searchQuery, shouldRequest]);

  // 请求数据
  async function getData(page) {
    const pageNo = page?.pageNo || 1;
    const pageSize = page?.pageSize || LIMIT;
    setPageNo(pageNo);
    setPageSize(pageSize);
    const { data } = await UserApi.getUserList(pageNo, pageSize, searchQuery);
    const { list, total } = data;
    return Promise.resolve({
      data: list,
      success: true,
      total: total
    });
  }

  function handleDelete(selectedRows) {
    if (selectedRows.length === 0) {
      ModalUtil.msgWarning('请选择要删除的用户');
      return;
    }
    ModalUtil.confirm(
      `确定要删除用户名为: ${selectedRows.map((row) => row.username).join('、')} 的这些用户？`,
      () => {
        UserApi.deleteUser(selectedRows.map((row) => row.userId)).then(({ code }) => {
          if (code === 0) {
            ModalUtil.msgSuccess('删除成功');
            tableRef.current?.request();
          }
        });
      }
    );
  }

  function onEdit(data) {
    formRef.current?.openEdit(data);
  }

  function onAdd() {
    formRef.current?.openAdd();
  }

  const render = (
    <>
      <UserFormModal
        ref={formRef}
        onRefresh={() => {
          tableRef?.current?.request();
        }}
      />
      <Card>
        <Flex vertical gap={SPACE}>
          <CustomTable
            ref={tableRef}
            rowKey="userId"
            title="用户列表"
            pagination={{
              pageSize,
              pageNo
            }}
            optionsWidth={45}
            onRowDelete={(row) => {
              handleDelete([row]);
            }}
            onDelete={handleDelete}
            onAdd={onAdd}
            onRowEdit={onEdit}
            onEdit={onEdit}
            rowSelection={rowSelection}
            columns={columns}
            request={getData}
            toolbar={renderToolbar()}
          />
        </Flex>
      </Card>
    </>
  );

  // 渲染工具栏
  function renderToolbar() {
    const width = 150;
    return (
      <>
        <Form
          form={searchForm}
          layout="inline"
          name="user-search"
          onValuesChange={(_, allValues) => {
            setSearchQuery(allValues);
          }}
          onFinish={() => {
            setShouldRequest(true);
          }}
        >
          <Form.Item label="用户ID" name="userId">
            <InputNumber min={1} placeholder="请输入用户ID" style={{ width: width }} />
          </Form.Item>
          <Form.Item label="用户名" name="username">
            <Input placeholder="请输入用户名" style={{ width: width }} />
          </Form.Item>
          <Form.Item>
            <Flex gap="small">
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
              <Button
                onClick={() => {
                  setSearchQuery({});
                  searchForm.resetFields();
                  setShouldRequest(true);
                }}
              >
                重置
              </Button>
            </Flex>
          </Form.Item>
        </Form>
      </>
    );
  }

  return <CustomPage>{render}</CustomPage>;
}
